extends Node2D

class_name PanaWorld

export (bool) var preview = false setget set_preview
export (PackedScene) var map_scene

var deploy_zone: Resource = preload("res://UIScenes/DeploymentZoneControl.tscn")
var deploy_zone_instance
var map : TileMap

func _ready():
	if map_scene:
		map = map_scene.instance()
		load_map(map)
	$Camera.make_current()
	reset()

func load_map(tm : TileMap):
	for c in $NavigationHandler.get_children():
		c.queue_free()
	deploy_zone_instance = deploy_zone.instance()
	$NavigationHandler.add_child(tm)
	deploy_zone_instance.resize_tm(tm)
	tm.add_child(deploy_zone_instance)
	map = tm
	$Cursor.tm = tm
	$Camera.position = tm.get_used_rect().get_center()
	
func load_map_from_name(map_path: String):
	var tm : TileMap = load(map_path).instance()
	load_map(tm)
	
func set_preview(v):
	preview = v
	$CanvasLayer/GameUI.visible = not preview
	$Camera.set_process(not preview)
	$Cursor.set_process(not preview)
	$Cursor.visible = not preview

func reset():
	$PlayerUnits.clear_units()
	$EnemyUnits.clear_units()

func _on_Cursor_place_unit(unit: Unit, pos):
	var u :Unit = unit.duplicate()
	$PlayerUnits.add_child(u)
	u.position = pos
	assert(u.get_node("AI").connect("request_path", self, "_on_AI_request_path") == OK)
	assert(u.get_node("AI").connect("order_done", $Order, "_on_AI_order_done") == OK)

func _on_AI_request_path(ai: UnitAI, dest: Vector2):
	ai.path = $NavigationHandler.get_simple_path(ai.unit.position, dest)
